<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>企业人事管理系统</span>
        </div>
      </template>

      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input
              v-model="form.phoneNumber"
              placeholder="请输入手机号"
              prefix-icon="el-icon-phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="encryptedPassword">
          <el-input
              type="password"
              v-model="form.encryptedPassword"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="rememberMe">记住账号密码</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" class="login-button">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="register-link">
        <router-link to="/HrmsRegister" text-align="center">没有账号？立即注册</router-link>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

const form = reactive({
  phoneNumber: '',
  encryptedPassword: ''
});
const rememberMe = ref(false);

const rules = {
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  encryptedPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

const ruleForm = ref(null);
const router = useRouter();

onMounted(() => {
  const savedPhoneNumber = localStorage.getItem('phoneNumber');
  const savedPassword = localStorage.getItem('encryptedPassword');
  if (savedPhoneNumber && savedPassword) {
    form.phoneNumber = savedPhoneNumber;
    form.encryptedPassword = savedPassword;
    rememberMe.value = true;
  }
});

const submitForm = () => {
  ruleForm.value.validate((valid) => {
    if (valid) {
      if (rememberMe.value) {
        localStorage.setItem('phoneNumber', form.phoneNumber);
        localStorage.setItem('encryptedPassword', form.encryptedPassword);
      } else {
        localStorage.removeItem('phoneNumber');
        localStorage.removeItem('encryptedPassword');
      }

      axios.post('http://localhost:8080/users/login', {
        phoneNumber: form.phoneNumber,
        encryptedPassword: form.encryptedPassword
      }).then(response => {
        if (response.data.code === 200) {
          ElMessage.success(response.data.message);
          const { token, userInfo } = response.data.data;
          sessionStorage.setItem('token', token);
          sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
          switch (userInfo.roleId) {
            case 1:
              router.push('/AdminUserIndex');
              break;
            case 2:
              router.push('/CommonUserIndex');
              break;
            case 3:
              router.push('/HrUserIndex');
              break;
            default:
              ElMessage.error('用户未认证，请联系管理员进行认证');
          }
        } else {
          ElMessage.error(response.data.message);
        }
      }).catch(error => {
        console.error('登录失败:', error);
        ElMessage.error('服务器错误');
      });
    } else {
      console.log('表单验证失败!!');
      return false;
    }
  });
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #74b9ff, #a29bfe);
}
.box-card {
  width: 500px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
}
.card-header {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}
.register-link {
  text-align: center;
  margin-top: 10px;
}
.demo-ruleForm {
  margin-top: 10px;
  width: 90%;
}
.login-button {
  width: 100%;
  background: linear-gradient(45deg, #0984e3, #74b9ff);
  color: white;
  border: none;

}
.login-button:hover {
  background: linear-gradient(45deg, #74b9ff, #0984e3);
}
</style>
